import { getApps, app2png } from './mac'
import fs from 'fs'
import path from 'path'
import os from 'os'
import iconPreference from '../../../resources/preference.png'

async function getAppIcon(appPath: string, name: string) {
  const icondir = path.join(os.tmpdir(), 'ProcessIcon') //TODO：临时目录会清理，需要改成永久目录
  if (!fs.existsSync(icondir)) {
    fs.mkdirSync(icondir)
  }

  const iconpath = path.join(icondir, `${name}.png`)
  const iconnone = path.join(icondir, `${name}.none`)

  const iconPathExists = fs.existsSync(iconpath)
  if (iconPathExists || fs.existsSync(iconnone)) {
    return iconPathExists
  }

  const ret = await app2png(appPath, iconpath)
  if (!ret.ok) {
    console.log(`app2png ${appPath} error: ${ret.error}`)
    fs.writeFileSync(iconnone, '')
    return false
  }
  return ret.ok
}

export async function GetApps(): Promise<AppInfo[]> {
  let apps = (await getApps()) as AppInfo[]

  apps = await Promise.all(
    apps.map(async (app) => {
      const iconExists = await getAppIcon(app.path, app.name)
      if (iconExists) {
        return {
          ...app,
          icon: 'image://' + path.join(os.tmpdir(), 'ProcessIcon', `${encodeURI(app.name)}.png`)
        }
      }

      if (app.path.includes('System Preferences.app')) {
        return {
          ...app,
          icon: iconPreference
        }
      }
      return app
    })
  )

  apps = apps.filter(Boolean).filter((app) => !!app.icon)

  return apps.map((app) => {
    // const appName = path.basename(app.path, path.extname(app.path))
    return app
  })
}
